<script lang="ts" setup>
import { ref, type PropType } from 'vue';
import type { FormInstance } from '@arco-design/web-vue/es/form';
import { $fetch } from '@/settings/utils/fetch';
import useNotification from '@/settings/hooks/notification';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  labelIds: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
});

const loading = ref(false);
const formData = ref({
  labelIds: props.labelIds,
});
const formRef = ref<FormInstance>();
const { success } = useNotification();
const { t } = useI18n();
const labelsListing = ref<Record<string, any>[]>([]);

const getLabels = async () => {
  const { isSuccess, data } = await $fetch('/admin/label/list');

  if (isSuccess) {
    labelsListing.value = data;
  }
};

const dialogClickButton = async (button: string) => {
  if (button !== 'ok') {
    return;
  }

  const res = await formRef.value?.validate();

  if (res) {
    return false;
  }

  const { isSuccess } = await $fetch('/admin/org/updateLabels', {
    method: 'post',
    data: {
      relationId: props.id,
      ...formData.value,
    },
  });

  if (isSuccess) {
    success(t('settings.notification.success'));
  }

  return isSuccess;
}

defineExpose({
  dialogClickButton,
});

getLabels();
</script>

<template>
  <AForm ref="formRef" auto-label-width scroll-to-first-error :model="formData">
    <ASpin :loading="loading">
      <AFormItem :label="$t('settings.view.organization.dialog.label.column1')" field="labelIds" :help="$t('settings.view.organization.dialog.label.help1')">
        <ASelect v-model="formData.labelIds" :fallback-option="false" multiple :limit="5">
          <AOption v-for="label in labelsListing" :key="label.labelId" :value="label.labelId">{{ label.labelName }}</AOption>
        </ASelect>
      </AFormItem>
    </ASpin>
  </AForm>
</template>

<style lang="scss" scoped>
</style>
